<?php

namespace app\common;

use app\BaseController;
use app\model\Config;
use app\model\User;
use app\Request;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Validate;

class Auth extends BaseController
{
	
	/**
	 * 获取密码加密后的字符串
	 * @param $password
	 * @param $salt
	 * @return string
	 */
	public static function getEncryptPassword($password, $salt = '')
	{
		return md5(md5($password) . $salt);
	}
	
	/**
	 * 存储用户Token
	 * @throws \Exception
	 */
	public static function setToken($data,$token): string
	{
		$exprie = 24 * 60 * 60 * 7;
		try {
			Cache::store('redis')->set($token, $data, $exprie);
			return true;
		}catch (\Exception $e){
			throw new \Exception('存储Token失败');
		}
	}
	
	/**
	 * 获取小程序Token
	 * @return mixed
	 */
	public static function getWeChatToken(){
		$appid = Config::getFieldByName('wechat_appid','value');
		$secret = Config::getFieldByName('wechat_secret','value');
		$token=Cache::store('redis')->get($appid);
		if ($token){
			return $token;
		}
		$data=http_request('https://api.weixin.qq.com/cgi-bin/token',['grant_type'=>'client_credential','appid'=>$appid,'secret'=>$secret],'post');
		$data=json_decode($data);
		Cache::store('redis')->set($appid, $data->access_token, 7000);
		return $data->access_token;
	}
	
	/**
	 * 修改密码
	 * @param string $newpassword       新密码
	 * @param string $oldpassword       旧密码
	 * @param bool   $ignoreoldpassword 忽略旧密码
	 * @return boolean
	 */
	public static function changepwd($newpassword,User $user, $oldpassword = '', $ignoreoldpassword = false)
	{
		//判断旧密码是否正确
		if ($user->password == self::getEncryptPassword($oldpassword,$user->salt) || $ignoreoldpassword) {
			Db::startTrans();
			try {
				$salt = build('alnum',6);
				$newpassword = self::getEncryptPassword($newpassword, $salt);
				$user->save(['loginfailure' => 0, 'password' => $newpassword, 'salt' => $salt]);
				//修改密码成功的事件
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				writeJson(0,'修改失败');
			}
			return true;
		} else {
			writeJson(0,'密码或用户名不正确');
		}
	}
	
}